#include "board.h"
#include "hotplug_manager.h"
#include "fs_manager.h"
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "sdmmc_cmd.h"

#define TAG "HOTPLUG_SD"

struct sdcard_detect_state_t {
	uint8_t prev_state;
	uint8_t stable_state;
	uint8_t detect_cnt;
};

static struct sdcard_detect_state_t sdcard_detect_state;

int _sdcard_get_state(void)
{
	int sdcard_state = HOTPLUG_NONE;

	if (sd_card_get_state()) {
		sdcard_state = HOTPLUG_IN;
	} else {
		sdcard_state = HOTPLUG_OUT;
	}

	return sdcard_state;
}

int _sdcard_hotplug_detect(void)
{
	int report_state = HOTPLUG_NONE;
	int state = HOTPLUG_NONE;

	state = _sdcard_get_state();

	if (state <= HOTPLUG_NONE) {
		goto exit;
	}

	if (state == sdcard_detect_state.prev_state) {
		sdcard_detect_state.detect_cnt++;
		if (sdcard_detect_state.detect_cnt >= 1) {
			sdcard_detect_state.detect_cnt = 0;
			if (state != sdcard_detect_state.stable_state) {
				sdcard_detect_state.stable_state = state;
				report_state = sdcard_detect_state.stable_state;
			}
		}
	} else {
		sdcard_detect_state.detect_cnt = 0;
		sdcard_detect_state.prev_state = state;
	}

exit:
	return report_state;
}

static int _sdcard_hotplug_fs_process(int device_state)
{
	int res = -1;

	switch (device_state) {
	case HOTPLUG_IN:
		// res = sd_sdiofs_mount();
		break;

	case HOTPLUG_OUT:
		res = sd_sdiofs_unmount();
		break;

	default:
		break;
	}

	return res;
}

static const struct hotplug_device_t sdcard_hotplug_device = {
	.type = HOTPLUG_SDCARD,
	.get_state = _sdcard_get_state,
	.hotplug_detect = _sdcard_hotplug_detect,
	.fs_process = _sdcard_hotplug_fs_process,
};

int hotplug_sdcard_init(void)
{
	memset(&sdcard_detect_state, 0, sizeof(struct sdcard_detect_state_t));

	if (fs_manager_get_sd_volume_state()) {
		sdcard_detect_state.stable_state = HOTPLUG_IN;
	} else {
		sdcard_detect_state.stable_state = HOTPLUG_OUT;
	}

	return hotplug_device_register(&sdcard_hotplug_device);
}
